<template>
  <div class="login">
    <!-- Form 组件提供了表单验证的功能，只需要通过 rules 属性传入约定的验证规则，并将 Form-Item 的 prop 属性设置为需校验的字段名即可。 -->
    <el-form ref="form" status-icon  :model="form" :rules="rules"  label-width="80px">
      <img class="logo" src="../assets/avatar.jpg" alt="">
      <el-form-item label="用户名"  prop='username'>
          <!-- .native 表示直接给组件的根元素, 绑定原生事件 -->
        <el-input  placeholder="请输入用户名"  v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="密码"  prop='password'>
        <el-input @keyup.enter.native='login' type='password'  placeholder="请输入密码"  v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item  prop='username'>
       <el-button @click='login'  class='loginBtn'   type='primary'>登录</el-button>
       <el-button @click='reset'>重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  data () {
    return {
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: ['blur', 'change'] },
          { min: 3, max: 12, message: '用户名必须是3-12位', trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: ['blur', 'change'] },
          { min: 3, max: 12, message: '密码必须是3-12位', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  methods: {
    reset () {
      this.$refs.form.resetFields()
    },
    login () {
      this.$refs.form.validate((valid) => {
        if (!valid) return
        axios.post('http://localhost:8888/api/private/v1/login', this.form).then(res => {
          const { meta, data } = res
          if (meta.status === 200) {
            const token = data.token
            localStorage.setItem('token', token)
            this.$message({
              message: meta.msg,
              type: 'success',
              duration: 1000,
              showClose: true
            })
            this.$router.push('/index')
          } else {
            this.$message({
              message: meta.msg,
              type: 'error',
              duration: 1000,
              showClose: true
            })
          }
        })
      })
    }
  }

}
</script>

<style  lang='scss'>
.login {
  width: 100%;
  height: 100%;
  background-color: #2d434c;
  overflow: hidden;

  .el-form {
    width: 400px;
    padding: 20px;
    padding-top: 70px;
    border-radius: 20px;
    background-color: #fff;
    margin: 0 auto;
    margin-top: 200px;
    position: relative;

    .logo {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      top: -70px;
      border-radius: 50%;
      border: 5px solid #fff;
    }

    .loginBtn {
      margin-right: 70px;
    }
  }
}
</style>
